import 'dart:async';
import 'dart:io';
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:video_player/video_player.dart';
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
import 'package:wallpaper/components/AlertDialog/circular_progress.dart';
import 'package:wallpaper/db/love_database.dart';

class VideoPlay extends StatefulWidget {
  final String smallPath;
  final String largePath;
  final String tags;
  final VoidCallback resetGetdata;
  final Function(String)? onVideoPathUpdate;
  final Function(double)? changeVideoRadio;
  const VideoPlay({
    super.key,
    required this.resetGetdata,
    required this.smallPath,
    required this.largePath,
    required this.tags,
    this.onVideoPathUpdate,
    this.changeVideoRadio,
  });

  @override
  State<VideoPlay> createState() => _VideoPlayState();
}

class _VideoPlayState extends State<VideoPlay> {
  late VideoPlayerController videoController;
  bool isLove = false;
  double iconSize = 30;
  bool init = false;
  double downloadProgress = 0.0;
  String videoPath = "";
  bool downloadCompleted = false; // 新增变量，标记下载是否完成
  final CancelToken _cancelToken = CancelToken();
  bool isOperation = true;

  @override
  void initState() {
    super.initState();
    _downloadAndInitializeVideo();
    isLoveGet();
    videoController = VideoPlayerController.asset('');
  }

  void isLoveGet() async {
    bool res = await context.read<LoveDatabase>().isLove(widget.smallPath);
    setState(() {
      isLove = res;
    });
  }

  void fileExists(String filePath) async {
    if (videoController.value.isInitialized) {
      videoController.dispose();
    }
    videoController = VideoPlayerController.file(File(filePath));
    await videoController.initialize();
    setState(() {
      init = true;
      videoPath = filePath;
      downloadCompleted = true; // 下载完成，设置为true
    });
    // 通知父组件视频路径已更新
    if (widget.onVideoPathUpdate != null) {
      widget.onVideoPathUpdate!(filePath);
    }
    videoController.play();
    videoController.setLooping(true);
    widget.changeVideoRadio?.call(videoController.value.aspectRatio);
  }

  void _downloadVideo(String filePath) async {
    try {
      final dio = Dio();
      await dio.download(
        widget.largePath,
        filePath,
        cancelToken: _cancelToken,
        onReceiveProgress: (received, total) {
          if (total != -1) {
            setState(() {
              downloadProgress = (received / total * 100);
            });
          }
        },
      );
      if (videoController.value.isInitialized) {
        videoController.dispose();
      }
      videoController = VideoPlayerController.file(File(filePath));
      await videoController.initialize();
      setState(() {
        init = true;
        videoPath = filePath;
        downloadCompleted = true; // 下载完成，设置为true
      });
      // 通知父组件视频路径已更新
      if (widget.onVideoPathUpdate != null) {
        widget.onVideoPathUpdate!(filePath);
      }
      videoController.play();
      videoController.setLooping(true);
      widget.changeVideoRadio?.call(videoController.value.aspectRatio);
    } catch (e) {
      print(e);
    }
  }

  Future<void> _downloadAndInitializeVideo() async {
    final directory = await getTemporaryDirectory();
    List names = widget.largePath.split('/');
    String name = names[names.length - 1];
    names.length > 1
        ? name = names[names.length - 2] + names[names.length - 1]
        : name = names[names.length - 1];
    final filePath = '${directory.path}/$name';

    try {
      if (await File(filePath).exists()) {
        fileExists(filePath);
      } else {
        _downloadVideo(filePath);
      }
    } catch (e) {
      // 出现错误时删除临时文件，重新初始化并下载视频一次
      deleteTempFile();
      setState(() {
        init = false;
        videoPath = '';
        downloadCompleted = false;
      });
      _downloadVideo(filePath);
      print('Error downloading video: $e');
      BotToast.showText(text: '$e');
    }
  }

  // 删除指定临时缓存文件
  void deleteTempFile() async {
    try {
      final directory = await getTemporaryDirectory();
      final filePath = '${directory.path}/${widget.largePath.split('/').last}';
      final file = File(filePath);
      if (await file.exists()) {
        await file.delete();
        print('Deleted temporary file: $filePath');
      } else {
        print('File does not exist: $filePath');
      }
    } catch (e) {
      print('Error deleting file: $e');
    }
  }

  @override
  void dispose() {
    videoController.dispose();
    // 取消下载任务
    _cancelToken.cancel("User left the page");

    // 如果下载未完成，则删除临时文件
    if (!downloadCompleted) {
      deleteTempFile();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: GestureDetector(
        onDoubleTap: () {
          if (init) {
            videoController.value.isPlaying
                ? videoController.pause()
                : videoController.play();
          }
        },
        child: Stack(
          children: [
            Center(
              child: init
                  ? AspectRatio(
                      aspectRatio: videoController.value.aspectRatio,
                      child: FittedBox(
                        fit: BoxFit.cover,
                        child: SizedBox(
                          width: videoController.value.size.width,
                          height: videoController.value.size.height,
                          child: VideoPlayer(videoController),
                        ),
                      ),
                    )
                  : Center(
                      child: AnimatedSwitcher(
                        duration: const Duration(milliseconds: 200),
                        transitionBuilder:
                            (Widget child, Animation<double> animation) {
                          return FadeTransition(
                            opacity: animation,
                            child: child,
                          );
                        },
                        child: downloadProgress / 100 == 0.0
                            ? const CircularProgressIndicator(
                                color: Colors.white,
                              )
                            : CircularProgress(
                                value: downloadProgress / 100,
                                radius: 18,
                              ),
                      ),
                    ),
            ),
          ],
        ),
      ),
    );
  }
}
